package com.miyake.dsp.osa.lab.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import com.miyake.dsp.osa.lab.AutoSetting;
import com.miyake.dsp.osa.lab.SettingPanelListener;

public abstract class AutoSettingPanelUI extends SettingPanelUI {
	public abstract void onRun();
	private AutoSetting setting;
	/**
	 * 
	 */
	private static final long serialVersionUID = 2934221104802332430L;
	
	class MyThread extends Thread {
		
		@Override
		public synchronized void start() {
			setting.setStop(false);
			setting.setInitial(true);
			super.start();
		}
		public void setStop() {
			setting.setStop(true);
		}
		@Override
		public void run() {
			while(!setting.isStop()) {
				if (setting.isReady()) {
					onRun();
				}
				try {
					Thread.sleep(setting.getInterval());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	};
	MyThread thread;
	
	@Override
	protected void createCustomComponent(final Object o) {
		setting = (AutoSetting)o;

		
		final JButton runButton = new JButton("Run");
		this.add(runButton);
		runButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				writeToObject();
				thread = new MyThread();
				thread.start();
				runButton.setEnabled(false);
			}
		
		});
		
		JButton stopButton = new JButton("Stop");
		this.add(stopButton);
		stopButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				thread.setStop();
				runButton.setEnabled(true);
			}
		
		});
		
		JButton resetButton = new JButton("Reset");
		this.add(resetButton);
		resetButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				setting.setStop(false);
				setting.setInitial(true);
			}
		
		});
	}

	public AutoSettingPanelUI(Object o, SettingPanelListener listener) {
		super(o, listener);
	}

	public AutoSettingPanelUI(Object o) {
		super(o);
	}

}
